<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片布局区域 -->
    <el-card class="box-card">
      <!-- 警告区域 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon :closable="false"></el-alert>

      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader v-model="selectCateKeys" :options="cateList" :props="cateProps" @change="cateListChange"></el-cascader>
        </el-col>
      </el-row>

      <!-- tabs 标签页区域 -->
      <!-- v-model 选中的标签页 name 值 -->
      <!-- tab-click 指 tab 页被选中时触发的事件 -->
      <el-tabs v-model="activeName" @tab-click="tabClick">
        <!-- label 选项卡标题 -->
        <!-- name 选项卡别名，方便对选项卡进行操作 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button @click="addDialogVisible = true" :disabled="isBtnDisabled" type="primary" plain>添加参数</el-button>
          <!-- 动态参数的表格 -->
          <el-table :data="manyTabData" style="width: 100%" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 渲染已有属性 -->
                <el-tag type="warning" closable v-for="(item, index) in scope.row.attr_vals" :key="index" @close="removeParams(idex, scope.row)">{{ item }}</el-tag>
                <!-- 添加新的属性 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button @click="showEditDialog(scope.row)" plain size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
                <el-button @click="deleteParams(scope.row.attr_id)" plain size="mini" type="danger" icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button @click="addDialogVisible = true" :disabled="isBtnDisabled" type="primary" plain>添加属性</el-button>
          <!-- 静态属性的表格 -->
          <el-table :data="onlyTabData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 渲染已有属性 -->
                <el-tag type="warning" closable v-for="(item, index) in scope.row.attr_vals" :key="index" @close="removeParams(idex, scope.row)">{{ item }}</el-tag>
                <!-- 添加新的属性 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button @click="showEditDialog(scope.row)" plain size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
                <el-button @click="deleteParams(scope.row.attr_id)" plain size="mini" type="danger" icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数或属性的弹框 -->
    <el-dialog :title="'添加' + textTitle" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
      <el-form :model="addParams" :rules="addParamsRules" ref="addParamsRef" label-width="100px">
        <el-form-item :label="textTitle" prop="attr_name">
          <el-input v-model="addParams.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParamsHandle">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑参数或属性的弹框 -->
    <el-dialog :title="'编辑' + textTitle" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <el-form :model="editParams" :rules="editParamsRules" ref="editParamsRef" label-width="100px">
        <el-form-item :label="textTitle" prop="attr_name">
          <el-input v-model="editParams.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParamsHandle">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Params',
  data() {
    return {
      // 商品分类数据列表
      cateList: [],
      // 级联选择器选中以后的值
      selectCateKeys: [],
      // 级联选择器配置项
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      activeName: 'many', // 被选中的tab
      manyTabData: [], // 动态参数的数据
      onlyTabData: [], // 静态属性的数据
      addDialogVisible: false, // 控制添加弹框的显示与隐藏
      // 添加动态参数或静态属性
      addParams: {
        attr_name: ''
      },
      // 添加验证规则
      addParamsRules: {
        attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      },
      editDialogVisible: false, // 控制编辑弹框的显示与隐藏
      // 编辑动态参数或静态属性
      editParams: {
        attr_name: ''
      },
      // 编辑验证规则
      editParamsRules: {
        attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      }
      // inputVisible: false, // 是否展示 input 输入框
      // inputValue: '' // 最新输入的属性值
    }
  },
  created() {
    // 调用获取商品分类的数据的方法
    this.getCateList()
  },
  methods: {
    // 获取商品分类的数据
    async getCateList() {
      const { data: res } = await this.$http.get('/categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
    },

    // 因为 tabs 切换 和 级联选择器 事件，调用的是同一份接口，
    // 所以可以抽取成一个方法，分别调用
    async getParamsData() {
      // 控制级联选择器的选择范围
      // 按照产品需求的要求，只允许为第三级分类设置相关参数
      if (this.selectCateKeys.length !== 3) {
        this.selectCateKeys = []
        this.manyTabData = []
        this.onlyTabData = []
        return false
      }

      const { data: res } = await this.$http.get(`/categories/${this.cateId}/attributes`, {
        params: { sel: this.activeName }
      })

      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)

      res.data.forEach(item => {
        // 如果 item.attr_vals 是空字符串，直接对其 .split(' ') ，
        // 会得到一个含有一个空字符串项的数组，所以需要进行三元判断
        // item.attr_vals = item.attr_vals.split(' ')
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []

        item.inputVisible = false
        item.inputValue = ''
      })

      if (this.activeName === 'many') {
        this.manyTabData = res.data
      } else {
        this.onlyTabData = res.data
      }
    },
    // 级联选择器选中的值改变以后触发
    async cateListChange() {
      this.getParamsData()
    },
    // tab 被选中时触发
    tabClick() {
      this.getParamsData()
    },
    // 关闭添加弹框，重置表单
    addDialogClosed() {
      this.$refs.addParamsRef.resetFields()
    },
    // 确认添加动态参数或静态属性
    addParamsHandle() {
      this.$refs.addParamsRef.validate(async valid => {
        if (!valid) return

        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addParams.attr_name,
          attr_sel: this.activeName
        })

        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.addDialogVisible = false
        this.getParamsData()
      })
    },

    // 关闭编辑弹框，重置表单
    editDialogClosed() {
      this.$refs.editParamsRef.resetFields()
    },
    // 获取当前分类的具体信息
    async showEditDialog(cateInfo) {
      const { data: res } = await this.$http.get(`/categories/${this.cateId}/attributes/${cateInfo.attr_id}`, {
        params: { attr_sel: this.activeName }
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editParams = res.data
      this.editDialogVisible = true
    },
    // 确认编辑动态参数或静态属性
    editParamsHandle() {
      this.$refs.editParamsRef.validate(async valid => {
        if (!valid) return

        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editParams.attr_id}`, {
          attr_name: this.editParams.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.editDialogVisible = false
        this.getParamsData()
      })
    },

    // 根据id，删除动态参数或静态属性
    async deleteParams(attrId) {
      const confirmResult = await this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('您取消了删除')
      }

      const { data: res } = await this.$http.delete(`/categories/${this.cateId}/attributes/${attrId}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.error(res.meta.msg)
      this.getParamsData()
    },

    // 展示 input 输入框
    showInput(paramsInfo) {
      paramsInfo.inputVisible = true

      // 想在整个DOM元素异步渲染以后，调用某一个方法
      this.$nextTick(() => {
        // 箭头函数无参数可以写()或者_
        // 使输入框呈现获取焦点状态
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // input 框失去焦点，按住 enter 键以后触发的事件
    handleInputConfirm(paramsInfo) {
      if (paramsInfo.inputValue.trim().length === 0) {
        paramsInfo.inputValue = ''
        paramsInfo.inputVisible = false

        return false
      }

      // 如果 inputValue 符合需求，就需要发起请求
      paramsInfo.attr_vals.push(paramsInfo.inputValue.trim())
      // paramsInfo.inputValue=''
      paramsInfo.inputVisible = false

      this.saveParams(paramsInfo)
      // this.getParamsData() // 可以不加
    },
    // 参数编辑操作
    async saveParams(paramsInfo) {
      const { data: res } = await this.$http.put(`/categories/${paramsInfo.cat_id}/attributes/${paramsInfo.attr_id}`, {
        attr_name: paramsInfo.attr_name,
        attr_sel: paramsInfo.attr_sel,
        attr_vals: paramsInfo.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      paramsInfo.inputValue = ''
    },
    // 删除分类参数
    removeParams(index, paramsInfo) {
      paramsInfo.attr_vals.splice(index, 1)
      this.saveParams(paramsInfo)
    }
  },
  computed: {
    // 控制按钮是否可禁用
    isBtnDisabled() {
      if (this.selectCateKeys.length !== 3) {
        return true
      }
      return false
    },
    // 获取分类参数的id
    cateId() {
      if (this.selectCateKeys.length === 3) {
        return this.selectCateKeys[2]
      }
      return null
    },
    textTitle() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt,
.el-tabs,
.el-table {
  margin: 15px 0;
}
.el-tag {
  margin: 10px;
}

.input-new-tag {
  width: 150px;
}
</style>
